<?php
namespace Home\Controller;
use Think\Controller;
/**
 * 注册控制器
 */
class RegController extends CommonController {
    /**
     * [index 注册首页]
     * @Author   Xuebingsi
     * @DateTime 2017-03-28T10:16:36+0800
     * @return   [type]                   [description]
     */
    public function index(){

        //获取随机一条人类验证
    	$question = D('verify')->getOneVerify();

    	$this->assign('question',$question);

        $this->assign('title',"注册");

        $this->display();
    }

    /**
     * [checkData 注册异步数据检查]
     * @Author   Xuebingsi
     * @DateTime 2017-03-28T10:16:50+0800
     * @return   [type]                   [description]
     */
    public function checkData()
    {
    	$password = I('post.password');
    	$repassword = I('post.repassword');

        //判断密码是否一致
    	if($password!=$repassword){
    		$arr = array(
    			'error'=>1,
    			'info'=>'两次密码不一致'
    			);
    		echo json_encode($arr);
    		exit;
    	}

    	$verify = I('post.verify');

        // 判断人类验证是否正确
    	if(md5($verify) != $_SESSION['answer']){
    		$arr = array(
    			'error'=>1,
    			'info'=>'人类验证不通过'
    			);
    		echo json_encode($arr);
    		exit;
    	}

        // 检测邮箱
    	if(D('user')->checkEmail(I('post.email'))){
    		$arr = array(
    			'error'=>1,
    			'info'=>'邮箱已存在'
    			);
    		echo json_encode($arr);
    		exit;
    	}

        //检测昵称
    	if(D('user')->checkNickname(I('post.nickname'))){
    		$arr = array(
    			'error'=>1,
    			'info'=>'昵称已存在'
    			);
    		echo json_encode($arr);
    		exit;
    	}

    	$data = I('post.');

    	$data['password']= md5($password);

    	$data['create_time']=time();

        $ip = "121.33.63.208";

        $data['city'] = $this->getCity($ip);

        // 增加用户
    	if(M('user')->add($data)){
    		$arr = array(
    			'error'=>0,
    			'info'=>'注册成功'
    			);
    		echo json_encode($arr);
    		exit;
    	}else{
    		$arr = array(
    			'error'=>1,
    			'info'=>'注册失败'
    			);
    		echo json_encode($arr);
    		exit;
    	}


    }

    public function getCity($ip)
    { 

       $url= "http://ip.taobao.com/service/getIpInfo.php?ip=".$ip;

       $data = file_get_contents($url);

       $arr = json_decode($data,true);

       if($arr['code']==0){
            return $arr['data']['city'];
       }

    }

    //获取访问者的ip
    public function ip()
    {
        $ip = get_client_ip();

        var_dump($ip);
    }
}
